<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\common\library\Token;
use app\dic\DicSite;
use PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Exp;
use think\App;
use think\facade\Log;
use util\Excel;
use util\Token as UtilToken;
use think\exception\ValidateException;

/**
 * Site控制器
 */
class Site extends AdminBase
{

    protected $model = null;

    protected $validate = null;

    protected $relationSearch = false;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\Site();

        $this->validate = \app\admin\validate\Site::class;
    }


    /**
     * 列表
     */
    public function index()
    {

        list($limit, $where, $sortArr) = $this->buildTableParames();

        $list = $this->model
            ->where($where)
            ->where(['status' => DicSite::$status_normal])
            ->order($sortArr)
            ->paginate($limit);
        $data = [
            'code' => 1,
            'msg' => '',
            'count' => $list->total(),
            'data' => $list->items(),
        ];

        return json($data);
    }

    /**
     * 下拉列表分页
     */
    public function selectPage()
    {
        $token = $this->request->header('token');
        //查询用户id
        // $adminId = UtilToken::userId($token);
        // $group_id = table('system_group')->field(['id'])->where(['admin_id' => $adminId])->find();
        // halt($group_id['id']);
        try {
            list($limit, $where, $sortArr) = $this->buildTableParames();

            $page = $this->request->get('page', 1);
            // $limit = $this->request->get('limit', 15);
            $limit = 100;
            $show_id = $this->request->get('show_id', 'id'); //前端显示的value
            $query_field = $this->request->get('query_field', 'name'); //查询的参数名称
            $show_field = $this->request->get('show_field', 'name'); //前端显示的label
            $keyword = $this->request->get('keyword', ''); //查询的参数值

            $query_value = $this->request->get('query_value', ''); //编辑查询检索的值

            if ($query_value) {
                $where[] = [$show_id, '=', $query_value];
            }
            if ($keyword) {
                $where[] = [$query_field, 'LIKE', "%{$keyword}%"];
            }

            $fields = $show_id . ',' . $show_field;
            // $where['status'] = 'normal';
            $adminId = UtilToken::userId($token);
            $group_id = table('system_group_admin')->field(['group_id'])->where(['admin_id' => $adminId])->find();
            if ($group_id['group_id'] == 5) {
                $where['adminid'] = $adminId;
            }
            $count = $this->model
                ->where($where)
                ->count();
            $datalist = $this->model
                ->field($fields)
                ->where($where)
                ->page($page, $limit)
                ->select();
            $list = [];
            foreach ($datalist as $index => $item) {
                $result = [
                    $show_id => isset($item[$show_id]) ? $item[$show_id] : '',
                    $show_field => isset($item[$show_field]) ? $item[$show_field] : '',
                ];
                $list[] = $result;
            }
            $data = [
                'code' => 1,
                'msg' => '',
                'count' => $count,
                'data' => $list,
            ];
            return json($data);
        } catch (\Exception $e) {
            Log::error("--------:" . $e);
            return error("获取数据失败");
        }
    }

    /**
     * 导出
     */
    public function export()
    {
        list($limit, $where, $sortArr) = $this->buildTableParames();
        $fields = $this->request->get('fields');
        $fields = json_decode($fields, true);

        $header = [];
        foreach ($fields as $vo) {
            $header[] = [$vo['comment'], $vo['field']];
        }
        $tableName = $this->model->getName();
        $list = $this->model
            ->where($where)
            ->limit(100000)
            ->order($sortArr)
            ->select()
            ->toArray();
        $fileName = "export_" . $tableName . "_" . time();
        halt($list, $header, $fileName);
        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }

    /**
     * 添加
     */
    public function add()
    {
        $post = $this->request->post();
        try {
            $this->validate && validate($this->validate)->check($post);
            if (!empty($post['advplat_id'])) {
                $post['advplat_id'] = implode(',', $post['advplat_id']);
            }
            $labels = $post['labels'];
            unset($post['labels']);
            $result = table('site')->insert($post);
            $site_id = table('site')->getlastInsId();
            if (!empty($labels)) {
                // 循环插入标签数据
                foreach ($labels as  $value) {
                    table('tags')->insert(
                        [
                            'admin_id' => $value['key'],
                            'tags' => $value['value'],
                            'site_id' => $site_id
                        ]
                    );
                }
            }
            if ($result) {
                return success('添加成功！');
            }
            return error('添加失败');
        } catch (ValidateException $e) {

            return error($e->getError());
        } catch (\Exception $e) {
            return error('添加失败:' . $e->getMessage());
        }
    }
    /**
     * 修改
     *
     */
    public function edit()
    {
        $id = input('id');
        $row = $this->model->find($id);
        if (empty($row)) {
            return error('数据不存在');
        }
        if ($this->request->isPost()) {
            $post = $this->request->post();
            try {
                $this->validate && validate($this->validate)->scene('edit')->check($post);
                if (!empty($post['advplat_id'])) {
                    // $post['advplat_id'] = json_encode($post['advplat_id'], true);
                    $post['advplat_id'] = implode(',', $post['advplat_id']);
                }

                // 修改标签运营
                $labels = $post['labels'];
                unset($post['labels']);
                $site_id = $post['id'];
                table('tags')->where(
                    [
                        'site_id' => $site_id
                    ]
                )->delete();
                if (!empty($labels)) {
                    // 循环插入标签数据
                    foreach ($labels as  $value) {
                        table('tags')->insert(
                            [
                                'admin_id' => $value['key'],
                                'tags' => $value['value'],
                                'site_id' => $site_id
                            ]
                        );
                    }
                }

                $result = $row->save($post);
                if ($result) {
                    return success('保存成功！');
                }
                return error('保存失败');
            } catch (ValidateException $e) {
                return error($e->getError());
            } catch (\Exception $e) {
                Log::error("--------:" . $e);
                return error('保存失败');
            }
        }
        $advplat_array = explode(',', $row['advplat_id']);
        foreach ($advplat_array as $key => $value) {
            $advplat_array[$key] = (int)$value;
        }
        $row['advplat_id'] = $advplat_array;
        $labels = table('tags')->where(['site_id' => $id])->select()->toarray();
        $labels2 = array();
        if (!empty($labels)) {
            foreach ($labels as $k => $v) {
                $labels2[$k]['key'] = (int)$v['admin_id'];
                $labels2[$k]['value'] = $v['tags'];
            }
        }
        if (empty($labels2)) {
            $labels2[0]['key'] = '';
            $labels2[0]['value'] = '';
            $labels2[1]['key'] = '';
            $labels2[1]['value'] = '';
        }
        $row['labels'] = $labels2;
        return success('ok', $row);
    }
}
